<template>
  <a-card :body-style="{padding: '0px 0px'}" :bordered="false">
    <a-space class="operator">
      <a-button @click="back" type="primary">返回上一页</a-button>
    </a-space>
    <a-steps class="steps" :current="stepCurrent" >
      <a-step :title="item.title" v-for="(item,index) in stepList" :key="index"/>
    </a-steps>

    <a-form-model v-if="stepCurrent == 0" :model="form" :layout="layout" style="margin-top:24px" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" ref="form"> 
      <a-form-model-item
        label="使用者"
        prop="name"
      >
        <a-input disabled v-model="form.name" placeholder="请填写使用者" autocomplete="off"/>
      </a-form-model-item>
      <a-form-model-item label="用户备注" >
        <a-textarea v-model="form.remark" placeholder="请填写用户备注" autocomplete="off" :rows="4"/>
      </a-form-model-item>
      <a-form-item :wrapperCol="{span: 17, offset: 7}">
        <a-button type="primary" @click="nextStep">下一步</a-button>
      </a-form-item>
    </a-form-model>
    <a-form-model v-if="stepCurrent == 1" :model="form" :layout="layout" style="margin-top:24px" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" ref="form">
      <a-form-model-item label="设备" prop="computer_id">
        <a-select v-model="form.computer_id" placeholder="请选择设备" :filter-option="filterOption">
          <a-select-option :value='form._computer_id' v-if="form._computer_id!=0">{{form.computername}}</a-select-option>
          <a-select-option v-for="(item,index) in kucunList" :key="index" :value='item.id'>{{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-item :wrapperCol="{span: 17, offset: 7}">
        <a-button type="primary" @click="nextStep">下一步</a-button>
        <a-button type="default" @click="stepCurrent--" style="margin-left:8px">上一步</a-button>
      </a-form-item>
    </a-form-model>
    <a-form-model v-if="stepCurrent == 2" :model="form" :layout="layout" style="margin-top:24px" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" ref="form">
      <a-form-model-item v-for="(item,index) in typeList2" :key="index" :label="item.name" >
        <a-select mode="multiple" :value="form[item.id] || []" :placeholder="'请选择'+item.name" @change="e=>peijianSelect(e,item.id)">
          <a-select-option value='0'>不选择</a-select-option>
          <a-select-option :value='item2.id.toString()' v-for="(item2,index2) in form[item.id+'name'] || []" :key="index2">{{item2.name}}</a-select-option>
          <a-select-option :value="item2.id" v-for="(item2,index2) in item.list" :key="index2">
            {{item2.name}}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-item :wrapperCol="{span: 17, offset: 7}">
        <a-button type="primary" @click="onSubmit">完成</a-button>
        <a-button type="default" @click="stepCurrent--" style="margin-left:8px">上一步</a-button>
      </a-form-item>
    </a-form-model> 
  </a-card>
</template>

<script>
import {editComputer} from '@/api/modules/list'
import {getPeijian,getComputer} from '@/api/modules/list_kucun'
import {getUser} from '@/api/modules/user'
import {group} from '@/api/modules/bumen'

export default {
  name: 'accountDetail',
  i18n: require('./i18n'),
  props:{
    mod:{
      type:String,
    },
    id:{
      type:[String,Number]
    },
    // typeList:{
    //   type:[Object,Array],
    //   default:()=>{}
    // },
  },
  data () {
    return {
      stepCurrent:0,
      stepList:[
        {id:1,title:'填写基础信息'},
        {id:2,title:'填写设备信息'},
        {id:3,title:'填写配件信息'}
      ],
      formItemLayout2: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 7 },
        },
      },

      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
      btn_wrapperCol:{ span: 13, offset: 7 },
      layout:'horizontal', //'horizontal'|'vertical'
      loading:false,
      groupList:[],
      groupListFirst:[],
      groupListSecond:[],
      form:{
        type:2,
        cname:'',
        uname:'',
        userid:'',
        jixing:'',
        peizhi:'',
        cpu:'',
        zhuban:'',
        neicun:'',
        xianka:'',
        yingpan:'',
        xianshiqi:[],
        shubiao:'',
        jianpan:'',
        ssd:'',
        qita:'',
        cremark:'',
        first:'',
        computer_id:'',
        uremark:'',
        second:0,
      },
      show_form:{
        type:2,
        cname:'',
        uname:'',
        jixing:'',
        peizhi:'',
        cpu:'',
        zhuban:'',
        neicun:'',
        xianka:'',
        yingpan:'',
        xianshiqi:'',
        shubiao:'',
        jianpan:'',
        ssd:'',
        qita:'',
        cremark:'',
        first:'',
        computer_id:'',
        uremark:'',
        second:0,
      },
      copy_form:{},
      options:{
        cpu:[],
        zhuban:[],
        neicun:[],
        xianka:[],
        yingpan:[],
        ssd:[],
      },
      kucunList:[],
      typeList:[],
      typeList2:[],
      userList:[],
      screenWidth: document.body.clientWidth, // 屏幕宽度
      rules:{
        cname:[
          {required: true,message: '请填写设备名', trigger: 'blur'}
        ],
        userid:[
          {required: true,message: '请填写用户名', trigger: 'blur'}
        ],
        first:[
          {required: true,message: '请选择一级部门', trigger: 'blur'}
        ],
        computer_id:[
          {required: true,message: '请选择设备', trigger: 'blur'}
        ],
      },
    }
  },
  created() {
    console.log('list-detail-add-created')
    this.init_created()
  },
  activated() {
    console.log('list-detail-add-activated')
    this.init_activated()
  },
  mounted() {
    this.changeLayout(document.body.clientWidth)
    window.onresize = () => {
      return (() => {
        this.screenWidth = document.body.clientWidth
      })()
    }
  },
  methods: {
    init_created(){
      // created请求的函数
      this.getDetail()
      this.getKucun()
      this.getTypeList()
    },
    init_activated(){
      // activated请求的函数
      this.getDetail()
      this.getKucun()
      this.getTypeList()
    },

    getType(id){
      switch(id){
        case 1:case '1':
          return 'cpu'
        case 2:case '2':
          return 'zhuban'
        case 3:case '3':
          return 'neicun'
        case 4:case '4':
          return 'xianka'
        case 5:case '5':
          return 'yingpan'
        case 6:case '6':
          return 'xianshiqi'
        case 7:case '7':
          return 'shubiao'
        case 8:case '8':
          return 'jianpan'
        case 9:case '9':
          return 'ssd'
        case 10:case '10':
          return 'qita'
      }
    },
    getTypeName(id){
      switch(id){
        case 1:case '1':
          return 'cpuname'
        case 2:case '2':
          return 'zhubanname'
        case 3:case '3':
          return 'neicunname'
        case 4:case '4':
          return 'xiankaname'
        case 5:case '5':
          return 'yingpanname'
        case 6:case '6':
          return 'xianshiqiname'
        case 7:case '7':
          return 'shubiaoname'
        case 8:case '8':
          return 'jianpanname'
        case 9:case '9':
          return 'ssd'
        case 10:case '10':
          return 'qitaname'
      }
    },
    getKucun(){ //获取库存电脑
      let params = {
        page:1,
        limit:99999,
      }
      getComputer(params).then((res) => {
        this.kucunList = res.data.data
      }).catch(() => {
        
      });

    },
    getTypeList(){ // 获取设备类型（cpu、主板...）
      // all 1：所有 2：电脑的 3：显示器键盘等
      // 2和3各获取一份
      getPeijian({all:2}).then((res) => {
        this.typeList = res.data
        getPeijian({all:3}).then((e) => {
          this.typeList2 = e.data
        }).catch(()=>{})
      }).catch(() => {});
    },
    getDetail(){ // 获取部门和详情
      editComputer({id:this.id}).then((res) => {
        this.form = res.data
        this.form['computer_id'] = res.data.computer_id || ''
        this.form['_computer_id'] = res.data.computer_id
        this.copy_form = JSON.parse(JSON.stringify(res.data)) 
        this.getSecondSelectList(res.data.first)
      }).catch(() => {
        
      });
    },
    getGroup(){ //获取部门
      group({}).then((e) => {
        this.groupList = e.data 
        this.groupListFirst = e.data.filter(e=>e.parent_id == 0)
        
      }).catch(() => {
      });
    },
    getUserfunc(){ //获取可配电脑的人
      let user_params = {
        page: 1,
        limit: 9999,
        status: 1,
        iscomputer: 1,
      }
      getUser(user_params).then(e=>{
        this.userList = e.data.data
      })
    },
    onSubmit(){
      if(this.id != 0){
        this.form.id = this.id
      }
      let form = JSON.parse(JSON.stringify(this.form))
      // 处理form,数组转字符串
      for(let item in form){
        if(Array.isArray(form[item])){
          form[item] = form[item].toString()
        }
      }
      this.$refs.form.validate((valid)=>{
        if(valid){
          this.loading = true;
          editComputer(form).then(() => {
            this.loading = false;
            this.$message.success('修改成功')
            this.back()
          }).catch(() => {
            this.loading = false;
          });
        }else{
          this.loading = false;
        }
      })
    },
    nextStep () {
      if (this.stepCurrent < 2) {
        this.$refs.form.validate((valid)=>{
          if(valid){
            this.stepCurrent += 1
          }
        })
      }
    },
    removeDomain(item) {
      let index = this.form.xianshiqi.indexOf(item);
      if (index !== -1) {
        this.form.xianshiqi.splice(index, 1);
      }
    },
    addDomain() {
      console.log(this.form.xianshiqi)
      let arr = this.form.xianshiqi || []
      arr.push({
        name: '',
        biaoshi: '',
        peizhi:'普通'
      });
      this.form.xianshiqi = arr
    },
    peijianSelect(val,id){
      console.log('peijianSelect',val,id)
      if(!val.find(i=>i=='0')){
        this.form[id] = val
      }else{
        this.form[id] = ['0']
      }
    },
    peijianSelect2(val,id){
      let options = this.options
      if(!val.find(i=>i=='0')){
        options[id] = [{value:'0',label:'不选择',key:'0'}]
        let fengefu = '-v-'; // 设置分隔符
        //获取真实val(不带 - 的)
        let real_val = []
        for(let item of val){
          real_val.push(item.split(fengefu)[0])
        }
        // console.log(val,real_val)
        // 根据real_val再推导出show_val和options
        let show_val = JSON.parse(JSON.stringify(real_val)) 
        for(let idx in show_val){
          let obj = {
            value:`${show_val[idx]+fengefu+idx}`,
            label:show_val[idx],
            key:`${show_val[idx]+idx}`
          }
          options[id].push(obj)
          show_val[idx] = show_val[idx]+fengefu+idx
        }
        // console.log(options,show_val)
        this.options = options
        this.show_form[id] = show_val
        //将正常数据给form
        this.form[id] = real_val
      }else{
        this.show_form[id] = ['0']
        this.form[id] = ['0']
        this.options = options
      }
    },
    getSecondSelectList(id){
      let arr = this.groupList.filter(e=>e.parent_id == id)
      this.groupListSecond = arr
    },
    back(){
      this.$emit('update:mod','normal')
    },
    changeLayout(e){
      if(e<=750){
        this.layout = 'vertical'
        this.labelCol = {}
        this.wrapperCol = {}
        this.btn_wrapperCol = {}
      }else{
        this.layout = 'horizontal'
        this.labelCol = {span: 7}
        this.wrapperCol = {span: 13}
        this.btn_wrapperCol = { span: 13, offset: 7 }
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
  },
  watch:{
    screenWidth(e){
      this.changeLayout(e)
    },
    'form.type'(e){
      let form = JSON.parse(JSON.stringify(this.form))
      if(e){
        form['type'] = e
        this.form = form;
      }
    }
  },
  computed: {
    desc() {
      return this.$t('pageDesc')
    },
    formItemLayout() {
      const layout  = this.layout;
      return layout === 'horizontal'
        ? {
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
          }
        : {};
    },
  }
}
</script>

<style scoped>
  .steps{
    max-width: 950px;
    margin: 16px auto;
  }
  .dynamic-delete-button {
    cursor: pointer;
    position: relative;
    top: 4px;
    font-size: 24px;
    color: #999;
    transition: all 0.3s;
  }
  .dynamic-delete-button:hover {
    color: #777;
  }
  .dynamic-delete-button[disabled] {
    cursor: not-allowed;
    opacity: 0.5;
  }
</style>
